package com.zyd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyd.controller.result.PageResult;
import com.zyd.controller.result.QueryPageBean;
import com.zyd.entity.CheckGroupSetmeal;
import com.zyd.entity.Setmeal;
import com.zyd.handle.BusinessException;
import com.zyd.mapper.SetmealMapper;
import com.zyd.service.CheckGroupSetmealService;
import com.zyd.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

import static com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery;


@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private CheckGroupSetmealService checkGroupSetmealService;

    @Override
    @Transactional
    public boolean addWithGroups(Setmeal setmeal, List<Integer> checkGroupIds) {
        // 1. 保存套餐
        if (!this.save(setmeal)) {
            throw new BusinessException("保存套餐失败");
        }

        // 2. 保存关联关系
        if (CollectionUtils.isNotEmpty(checkGroupIds)) {
            saveRelations(setmeal.getId(), checkGroupIds);

            System.out.println(" 保存关联关系------------------"+setmeal.getId()+ "checkGroupIds : " + checkGroupIds);
        }
        return true;
    }

    @Override
    @Transactional
    public boolean updateWithGroups(Setmeal setmeal, List<Integer> checkGroupIds) {
        // 1. 更新套餐
        if (!this.updateById(setmeal)) {
            throw new BusinessException("更新套餐失败");
        }

        // 2. 更新关联关系（先删后增）
        checkGroupSetmealService.removeBySetmealId(setmeal.getId());

        // 3. 保存新关联关系
        if (CollectionUtils.isNotEmpty(checkGroupIds)) {
            saveRelations(setmeal.getId(), checkGroupIds);
        }
        return true;
    }

    @Override
    public boolean deleteWithGroups(Integer id) {
        // 1. 删除关联关系
        checkGroupSetmealService.removeBySetmealId(id);

        // 2. 删除套餐
        return this.removeById(id);
    }

    // 私有方法：保存关联关系
    private void saveRelations(Integer setmealId, List<Integer> checkGroupIds) {
        List<CheckGroupSetmeal> relations = checkGroupIds.stream()
                .map(groupId -> new CheckGroupSetmeal(setmealId, groupId))
                .collect(Collectors.toList());

        if (!checkGroupSetmealService.saveBatch(relations)) {
            throw new BusinessException("保存套餐-检查组关系失败");
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        try {
            // 参数校验
            if (queryPageBean == null) {
                queryPageBean = new QueryPageBean(); // 提供默认值
                queryPageBean.setCurrentPage(1);
                queryPageBean.setPageSize(10);
            }
            if (queryPageBean.getCurrentPage() <= 0) {
                queryPageBean.setCurrentPage(1);
            }
            if (queryPageBean.getPageSize() <= 0) {
                queryPageBean.setPageSize(10);
            }

            // 分页查询
            IPage<Setmeal> page = new Page<>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
            QueryWrapper<Setmeal> wrapper = new QueryWrapper<>();

            if (StringUtils.isNotBlank(queryPageBean.getQueryString())) {
                String query = queryPageBean.getQueryString().trim();
                wrapper.like("name", query)
                        .or().like("code", query)
                        .or().like("helpCode", query);
            }

            IPage<Setmeal> result = this.page(page, wrapper);
            return new PageResult(result.getTotal(), result.getRecords());
        } catch (Exception e) {
            log.error("套餐分页查询失败", e);
            throw new RuntimeException("系统繁忙，请稍后重试");
        }
    }

    @Override
    public boolean add(Setmeal setmeal) {
        // 校验套餐编码唯一性
        if (lambdaQuery().eq(Setmeal::getCode, setmeal.getCode()).exists()) {
            throw new BusinessException("套餐编码已存在");
        }

        // 设置默认值（如适用性别未填时设为"0-不限"）
        if (StringUtils.isBlank(setmeal.getSex())) {
            setmeal.setSex("0");
        }

        return this.save(setmeal);
    }

    @Override
    @Transactional
    public boolean deleteById(Integer id) {
        // 1. 校验套餐是否存在
        Setmeal setmeal = this.getById(id);
        if (setmeal == null) {
            throw new BusinessException("套餐不存在或已被删除");
        }

        // 2. 删除关联的检查组关系（需先删除）
        // checkGroupSetmealService.removeBySetmealId(id); // 若有多对多关系需启用

        // 3. 删除套餐本身
        return this.removeById(id);
    }

    @Override
    public boolean update(Setmeal setmeal) {
        // 1. 校验套餐是否存在
        if (this.getById(setmeal.getId()) == null) {
            throw new BusinessException("套餐不存在");
        }

        // 2. 校验编码唯一性（排除自身）
        boolean exists = this.lambdaQuery()
                .eq(Setmeal::getCode, setmeal.getCode())
                .ne(Setmeal::getId, setmeal.getId())
                .exists(); // 正确调用exists()
        if (exists) {
            throw new BusinessException("套餐编码已被其他套餐使用");
        }

        // 3. 执行更新
        return this.updateById(setmeal);
    }





}